package controllers

import (
	"bolg_admin/app/models/user"
	"bolg_admin/pkg/jwt"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Date 定义响应结构体
type Date struct {
	Code  string      `json:"code"`
	Msg   string      `json:"msg"`
	Token string      `json:"token"`
	Data  interface{} `json:"data"`
}

type LoginData struct {
	Name     string ` json:"name" binding:"required"`
	Password string ` json:"password" binding:"required"`
}

func Register(c *gin.Context) {
	name := c.PostForm("name")
	email := c.PostForm("email")
	password := c.PostForm("password")
	// 1. 表单验证
	// 2. 验证通过 —— 入库，并跳转到首页
	_user := user.User{
		Name:     name,
		Email:    email,
		Password: password,
	}
	err := _user.Create()
	if err != nil {
		return
	}
	result := Date{
		"200",
		"注册成功",
		"",
		nil,
	}
	fmt.Println(result)
	c.JSON(200, result)
}

func Login(c *gin.Context) {
	var json LoginData
	if err := c.ShouldBindJSON(&json); err != nil {
		// 返回错误信息
		// gin.H封装了生成json数据的工具
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	userData, ok := user.GetByName(json.Name, json.Password)
	token, _ := jwt.ReleaseToken(userData)
	var result Date
	if !ok {
		result = Date{
			"400",
			"登录失败",
			"",
			nil,
		}
	} else {
		result = Date{
			"200",
			"登录成功",
			token,
			userData,
		}
	}

	c.JSON(200, result)
}

func GetInf(c *gin.Context) {
	fmt.Println(c)
	id, _ := c.Get("userId")
	//id := c.PostForm("id")
	fmt.Println(id)
	inf, err := user.GetUserInf(id)
	if err != nil {
		return
	}
	result := Date{
		"200",
		"成功",
		"",
		inf,
	}
	c.JSON(200, result)
}
